<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue'
const internalInstance = getCurrentInstance()
// 批量创建WebSocket
const map_wss = ref([])
async function creatWebSocket() {
  let ws
  for (let index = 0; index < 20; index++) {
    ws = new WebsocketBuild('wss://m.superbest.wang/wss/')
    map_wss.value.push(ws)
    ws.onopen = () => {
      //操作数据后更新视图
      internalInstance.proxy.$forceUpdate()
    }
    ws.onclose = () => {
      //操作数据后更新视图
      internalInstance.proxy.$forceUpdate()
    }
  }
  window.map_wss = map_wss
}
setInterval(() => {
  if (map_wss.value.length > 0) {
    //操作数据后更新视图
    internalInstance.proxy.$forceUpdate()
  }
}, 1000)

async function destroyWebSocket(index) {
  if (map_wss.value[index]) {
    map_wss.value[index].close()
    map_wss.value.splice(index, 1)
    internalInstance.proxy.$forceUpdate()
  }
}

const tableRowClassName = ({ rowIndex }) => {
  // if (rowIndex % 2 == 0) {
  //   return 'warning-row'
  // } else {
  //   return 'success-row'
  // }
  return ''
}
let columns = ref([])
let tableData = ref([])
let total = ref(0)
let pageIndex = ref(1)
let pageSize = ref(10)
let loading = ref(false)
columns.value.push(
  ...[
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'equipmentId',
      label: '渠道'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'user_id',
      label: '设备Id'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'name',
      label: '设备名称'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'remarks',
      label: '备注'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'createdAt',
      label: '创建时间'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'updatedAt',
      label: '更新时间'
    },
    {
      align: 'center',
      width: '',
      show: true,
      prop: 'date',
      label: '操作'
    }
  ]
)

/**
 *
 * @returns 获取采集设备列表
 *
 */
async function getDouyinAccountList() {
  loading.value = true
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  let DouYionEquipment = `http://208.87.207.213:38390/CloudUser/DouyinAccountList?sgin=47CFD0A2EB7EA1DC043F1B91926890E9&status=0%2C1%2C-1&page=${pageIndex.value}&pageNo=${pageSize.value}`
  // const SendData = {}
  const response_ = await fetch(DouYionEquipment, {
    method: 'GET',
    headers: {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: undefined
  })
  let response = await response_.json()
  localStorage.setItem('DouyinAccountList', JSON.stringify(response.data))
  loading.value = false
  console.warn(response.data)
  total.value = response.data.count
  tableData.value = response.data.rows
}

let UpdateMessage = ref('')
onMounted(async () => {
  let DouyinAccountList = localStorage.getItem('DouyinAccountList')
  if (DouyinAccountList) {
    DouyinAccountList = JSON.parse(DouyinAccountList)
    total.value = DouyinAccountList.count
    tableData.value = DouyinAccountList.rows
  } else {
    await getDouyinAccountList()
  }

  if (electron) {
    electron.ipcRenderer.on('UpdateMessage', (data) => {
      console.warn(data)
      UpdateMessage.value = JSON.stringify(data)
    })
  }
})

async function handleCurrentChange(number) {
  console.warn('handleCurrentChange', number)
  pageIndex.value = number
  await getDouyinAccountList()
}

class WebsocketBuild {
  // websocket对象
  ws = null
  // websocket地址
  wsServer = ''
  // 断线重连次数
  limitConnect = 50
  // 累计断线重连次数
  timeConnect = 0
  // websocket binaryType
  binaryType = 'arraybuffer'
  // 定时器
  Interva = null
  // 直播间在线人数
  onlineUserForAnchor = 0
  constructor(wsServer) {
    this.wsServer = wsServer
    this.webSocketStart(this.wsServer)
  }
  HeartBeat = () => {
    // 心跳 * 回应
    this.Interva = setInterval(() => {
      if (this.ws) {
        //CONNECTING：值为0，表示正在连接。
        //OPEN：值为1，表示连接成功，可以通信了。
        //CLOSING：值为2，表示连接正在关闭。
        //CLOSED：值为3，表示连接已经关闭，或者打开连接失败。
        if (this.ws.readyState === 1) {
          this.ws.send('发送心跳响应')
          console.warn('发送心跳响应-----')
        }
      }
    }, 5000)
  }
  webSocketStart = () => {
    this.ws = new WebSocket(this.wsServer)
    this.ws.binaryType = 'arraybuffer'
    this.ws.onmessage = this.onmessage
    this.ws.onclose = this.onclose
    this.ws.onopen = this.onopen
  }
  onmessage = (msg) => {
    console.log('wss服务器消息')
    this.ws.send('hello')
  }
  onclose = () => {
    console.log('wss服务器已经断开')
    this.reconnect(this.wsServer)
  }
  onopen = () => {
    console.log('已连接wss服务器')
    this.HeartBeat()
  }
  reconnect = () => {
    // lockReconnect加锁，防止onclose、onerror两次重连
    if (this.limitConnect > 0) {
      this.limitConnect--
      this.timeConnect++
      console.log('第' + this.timeConnect + '次重连')
      // 进行重连
      setTimeout(() => {
        this.webSocketStart(this.wsServer)
      }, 2000)
    } else {
      console.log('wss连接已超时')
    }
  }
}
/**
 *
 * @param {检查更新软件操作} cmd
 */
// eslint-disable-next-line no-unused-vars
async function checkForUpdate(cmd) {
  if (electron) {
    electron.ipcRenderer.send('checkForUpdate', true)
  }
}
</script>

<template>
  <div class="container no-drag">
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      empty-text="暂无数据"
      border
      row-key="id"
      size="large"
      style="width: 100%"
      highlight-current-row
      :header-cell-style="{ background: '#F9F9F9', color: '#606266' }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align"
        :show-overflow-tooltip="true"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
      />
      <template #scope>
        <div>
          {{ scope.row[item.prop] }}
        </div>
      </template>
    </el-table>
    <el-button class="no-drag" type="danger" @click="checkForUpdate">检查更新</el-button>
    <el-button type="primary" size="small" @click="getDouyinAccountList">更新设备列表</el-button>
    <!-- 合计统计显示 -->
    <div class="total_tatistics">
      <span>总设备数：{{ total || '0' }} </span>
    </div>
    <div class="pagination">
      <el-pagination
        :current-page="pageIndex"
        layout=" prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        background
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 直播任务信息 -->
    <div class="live">
      <span>直播任务信息:</span>
      <button @click="creatWebSocket">创建WebSocket</button>
      <div v-for="(item, index) in map_wss" :key="index" class="">
        <button @click="destroyWebSocket(index)">销毁WebSocket</button>
        {{ item.readyState }}
      </div>
    </div>
  </div>
</template>

<style lang="less">
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.total_tatistics {
  padding: 12px;
  font-family: auto;
  font-size: 15px;
  font-weight: bold;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 19px;
}
</style>
